package cn.com.mvc.controller;

import java.lang.reflect.Method;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static final String  controller_Package= "controllerPackage";
	static final String  handler_Mapping= "handlerMapping";

	@Override
	public void init() {
		System.out.println("=====init starting=====");
		String packagePath = this.getInitParameter(controller_Package);
		System.out.println(packagePath);
		String[] packages = packagePath.split(",");
		HashMap<String, HandlerMapping> handleMaps = HandlerMapping.initMappings(packages);
		this.getServletContext().setAttribute(handler_Mapping, handleMaps);
		System.out.println(handleMaps); 
		System.out.println("=====init ending=====");
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpServiceRestful(request,response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void HttpServiceRestful(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String uri = request.getRequestURI();
		System.out.println("=====requesting " + uri);
		String[] keys = uri.split("/");
		String controllerName = keys[1];
		String methodName=keys[2];
		HashMap<String, HandlerMapping> handleMaps = this.getHandlerMappings();
		HandlerMapping handlerMapping = handleMaps.get(controllerName);
		Method handlerMethod=handlerMapping.getHandlers().get(methodName);
		System.out.println(handlerMapping.getClazz());
		System.out.println(handlerMethod);
		String viewerURL = (String)handlerMethod.invoke(handlerMapping.getClazz().newInstance(),new Object[]{request,response});
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(viewerURL);
		requestDispatcher.forward(request, response);
	}
	
	@SuppressWarnings("unchecked")
	HashMap<String, HandlerMapping> getHandlerMappings(){
		return (HashMap<String, HandlerMapping>)this.getServletContext().getAttribute(handler_Mapping);
	}
}
